package com.sprite.framework.bone;

import com.sprite.framework.component.SpriteConfig;
import com.sprite.framework.context.ContextEnvironment;
import com.sprite.framework.entity.EntityLoader;
import com.sprite.framework.entity.EntityScriptExecutor;
import com.sprite.framework.start.Container;
import com.sprite.utils.UtilCollection;
import com.sprite.utils.UtilMisc;
import com.sprite.utils.UtilString;
import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Sprite 启动器
 */
public class SpriteContainer implements Container {

	private Logger logger = LoggerFactory.getLogger(SpriteContainer.class);

	List<String> loaderList = UtilMisc.toList("main");

	private CommandLine cmdLine;

	private boolean updateDb;	// 是否安装数据库

	@Override
	public void init(String[] args) {
		Options options = new Options().addOption("loaders", true, "main, demo, default value is main");
		options.addOption("sqltype", true, "default sql type : mysql, support mysql,oracle,pgsql,sqlserver,sqlserver2012");
		options.addOption("install", false, "install db");

		CommandLineParser parser = new DefaultParser();
		// 解析命令行参数
		try {
			cmdLine = parser.parse(options, args);
		} catch (ParseException e) {
			throw new RuntimeException(e);
		}

		loaderList.add("main");

		if(this.cmdLine.hasOption("loaders")){
			String option = this.cmdLine.getOptionValue("loaders");
			loaderList.addAll(UtilString.commaDelimiteToStringList(option));
		}

		updateDb = this.cmdLine.hasOption("install");
	}

	@Override
	public void start() {
		List<SpriteConfig> componentConfigs;
		try {
			componentConfigs = SpriteConfig.getAllComponents();


			if(UtilCollection.isEmpty(componentConfigs)){
				logger.info("[SpriteContainer] not found sprite.xml");
				return;
			}
		
			for(SpriteConfig spriteConfig : componentConfigs) {
				spriteConfig.configure(loaderList);
			}


			String sqlType = cmdLine.getOptionValue("sqltype");
			if(sqlType == null) {
				sqlType = ContextEnvironment.getProperty("sprite.sqltype");
			}

			if(UtilString.isBlank(sqlType)) {
				throw new Exception("not specified sql type ");
			}

			EntityLoader entityLoader = new EntityLoader();
			entityLoader.setEntityScriptExecutor(SpringContextUtil.getBean(EntityScriptExecutor.class));
			entityLoader.setSqlType(sqlType);

			entityLoader.loadEntityModel(updateDb);
			entityLoader.loadEntityData();

			if(updateDb){
				logger.info("load success");
				System.exit(0);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void stop() {
		// TODO Auto-generated method stub

	}

}
